package com.yuwenlong;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import android.widget.ImageView;

import com.liao.liaowenlong.R;

public class ItemListViewLayoutAdapter extends BaseAdapter {

    private List<BookInfo> books;

    private Context context;
    private LayoutInflater layoutInflater;
    private CallBack callBack;

    public ItemListViewLayoutAdapter(Context context, ArrayList<BookInfo> books, CallBack callBack) {
        this.context = context;
        this.books = books;
        this.callBack = callBack;
        this.layoutInflater = LayoutInflater.from(context);
    }

    @Override
    public int getCount() {
        return books.size();
    }

    @Override
    public BookInfo getItem(int position) {
        return books.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        if (convertView == null) {
            convertView = layoutInflater.inflate(R.layout.iten_listview_layout, null);
            convertView.setTag(new ViewHolder(convertView));
        }
        initializeViews(getItem(position), (ViewHolder) convertView.getTag());
        return convertView;
    }

    private void initializeViews(final BookInfo book, ViewHolder holder) {
        holder.imgDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                callBack.delete(book);
            }
        });
        System.out.println("ItemListViewLayoutAdapter.initializeViews" + books);
        holder.tvName.setText(book.getName());
        holder.tvAuthor.setText(book.getAuthor());
        holder.tvSum.setText(String.valueOf(book.getSum()));
    }

    public interface CallBack {
        void delete(BookInfo bookInfo);
    }

    protected class ViewHolder {
        private TextView tvName;
        private TextView tvAuthor;
        private TextView tvSum;
        private ImageView imgDelete;

        public ViewHolder(View view) {
            tvName = (TextView) view.findViewById(R.id.tv_name);
            tvAuthor = (TextView) view.findViewById(R.id.tv_author);
            tvSum = (TextView) view.findViewById(R.id.tv_sum);
            imgDelete = (ImageView) view.findViewById(R.id.img_delete);
        }
    }
}
